﻿import VTitle from '@/components/common/MainTitle.vue'
import ShowMetaFormItemLayout from '@/components/MetaFormItemComponents/MetaFormLayoutComponents.vue'
// 引入关联的页面弹窗
import MetaWorkflowMenuDialog from './MetaWorkflowMenuDialog.vue'
// 展示审核步骤的页面
import stepsShow from '@/views/workflow/workflowShow/StepsInfo.vue'
// 展示流程图的页面
import workflowShow from '@/views/workflow/workflowShow/WorkflowShow.vue'
// 引入公共的基础部分
import ExtendWorkflow from '@/components/extendComponents/ExtendMetaWorkflow.vue'
// 引入选人的弹窗
import ChooseUsers from '@/components/ChooseUser.vue'
export default {
  extends: ExtendWorkflow,
  components: {
    VTitle, ShowMetaFormItemLayout, MetaWorkflowMenuDialog, workflowShow, stepsShow, ChooseUsers
  },
  data () {
    return {
      titleName: '',
      // 页面的表单的uid
      dynamicUid: '',
      // 关联的页面弹窗
      relatedPageUid: '',
      retatedPageVisible: false,
      clickRow: '',
      dialogType: ''
    }
  },
  created () {
    this.init()
  },
  methods: {
    // 初始化页面
    init () {
      this.loading = true
      this.models = {}
      this.rules = {}
      this.allSingleElement = []
      this.clickRow = ''
      this.dialogType = ''
      this.pageFormInfo = ''
      this.currentShow = 'basicInfo'
      this.dynamicUid = this.$route.query.uid
      this.workflowBtnStatus = {
        Delete: [],
        Save_add: [],
        Save_edit: [],
        Submit: [],
        Pass: [],
        Reject: [],
        SelectReject: [],
        Stop: [],
        Apply: [],
        SubmitPending: [],
        ActivePending: []
      }
      this.pagePrimaryObj = {
        inputArray: [],
        outputArray: []
      }
      this.workFlowParams = {
        primaryKey: '',
        status: '',
      }
      this.currentEventsArray = []
      // 对于特殊的需要选人的节点
      this.NextUserList = null
      this.currentClickType = ''
      this.showUserDialog = false
      this.getFunInfo(this.dynamicUid)
    },
    // 获取功能的设定信息---定义好表头及功能的基本信息
    getFunInfo (uid) {
      this.$basicWFGet('/d_form/' + uid).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.loading = false
          this.$message({
            message: dataInfo.msg,
            type: 'error'
          })
        }
        if (dataInfo.code === 'success') {
          this.titleName = dataInfo.data.name
          if (dataInfo.data.is_warnning) {
            this.$message({
              type: 'warning',
              message: dataInfo.data.warnning_msg,
              showClose: true,
              duration: 0
            })
          } else if (dataInfo.data.is_error) {
            this.$message({
              type: 'error',
              message: dataInfo.data.error_msg
            })
            this.loading = false
          }
          if (dataInfo.data.settings && !dataInfo.data.is_error) {
            this.pageFormInfo = JSON.parse(dataInfo.data.settings)
            // 获取流程表单的按钮显示状态和按钮事件
            this.getWorkflowBtnStatus(this.pageFormInfo.pageConfig)
            // 当页面有初始化事件时
            this.currentEventsArray = []
            // 先在固有事件中查找
            if (this.pageFormInfo.pageConfig.inherentEvents.length) {
              this.pageFormInfo.pageConfig.inherentEvents.forEach(item => {
                if (item.eventsType === 'initPage' && item.isActive) {
                  this.currentEventsArray.push(item)
                }
              })
            }
            // 在自定义事件中查找
            if (this.pageFormInfo.pageConfig.events.length) {
              this.pageFormInfo.pageConfig.events.forEach(item => {
                if (item.eventsType === 'initPage' && item.isActive) {
                  this.currentEventsArray.push(item)
                }
              })
            }
            // 获取表单的基本信息
            this.getFormInfo(this.pageFormInfo.list)
            this.changeModels = !this.changeModels
            // 如果有页面初始化事件，就执行
            if (this.currentEventsArray.length) {
              this.currentEventsArray.sort(this.orderByObjAttr('actionIndex'))
              // 根据事件编号获取事件详细---事件编号、是否是初始化事件(事件类型)、事件执行的顺序、元数据表的uid、流程事件的类别（delete/save/submit/pass/reject/stop
              this.getEventsInfoByEventNo(this.currentEventsArray[0].eventsNo, 'isInit', 1, this.pageFormInfo.pageConfig.refMainMetaTableUid, null)
            } else {
              this.loading = false
            }
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 触发事件后执行的结果
    afterEval (dataInfo, eventType, eventItemNo, evalIndex, evalMetauid, workflowEventItem) {
      if (dataInfo.code === 'failed') {
        this.loading = false
        this.$message({
          message: dataInfo.msg,
          type: 'warning'
        })
      } else if (dataInfo.code === 'success') {
        // 触发事件后，需要判断获取的值是否需要用到下一个事件中
        this.changeOutputParames(dataInfo.data, eventItemNo)
        // 如果是最后一个事件
        if (this.currentEventsArray.length === evalIndex) {
          this.currentEventsArray = []
          // 当为流程类的事件时
          if (workflowEventItem) {
            this.loading = false
            let msg = (workflowEventItem.eventType === 'Save_add' || workflowEventItem.eventType === 'Save_edit') ? '保存成功' : ( workflowEventItem.eventType === 'Delete' ? '删除成功' : '操作成功')
            this.$confirm(msg, '提示', {
              showClose: false,
              showCancelButton: false,
              closeOnClickModal: false,
              closeOnPressEscape: false,
              confirmButtonText: '确定'
            }).then(() => {
              // 保存时不需要刷新窗口
              // if (workflowEventItem.eventType !== 'Save_add' && workflowEventItem.eventType !== 'Save_edit') {
              //   this.init()
              // }
              this.init()
            }).catch(() => {})
          } else {
            // 非流程类的事件时
            if (eventType === 'isInit') {
              // 初始化事件时
              this.$nextTick(() => {
                if (dataInfo.data && !this.$isEmptyObject(this.models)) {
                  let dataObj = dataInfo.data
                  if (this.$isArray(dataInfo.data)) {
                    dataObj = dataInfo.data[0]
                  }
                  for (let rowKey in dataObj) {
                    for (let modelKey in this.models) {
                      if (modelKey === rowKey) {
                        this.$set(this.models, modelKey, dataObj[rowKey])
                      }
                    }
                  }
                }
                this.pageInit = !this.pageInit
              })
              this.loading = false
            } else {
              // 其他事件时
              this.$message({
                message: dataInfo.msg,
                type: 'success'
              })
              this.init()
            }
          }
        // 还有其它事件需要执行时
        } else {
          this.judgeNextEvent(eventType, eventItemNo, evalIndex, evalMetauid, workflowEventItem)
        }
      } else if (dataCode === 'failedToClose') {
        this.loading = false
        this.currentEventsArray = []
        this.$message({
          message: dataInfo.msg,
          type: 'success'
        })
        this.init()
      }
    },
    // 取消表单提交时
    resetFormData () {
      this.$refs['formMenuLayout'].resetValidate()
    },
    // 处理行事件时
    handelRowEvents (fromChildItem) {
      if (fromChildItem && fromChildItem.eventsArray && fromChildItem.eventsArray.length) {
        this.loading = true
        this.clickRow = fromChildItem.clickRow
        this.currentEventsArray = JSON.parse(JSON.stringify(fromChildItem.eventsArray))
        // 当执行的是固有事件时
        if (this.currentEventsArray[0].actionIndex === 0) {
          if (this.currentEventsArray[0].eventsType === 'deleteTable') {
            this.evalTableDeleteRowMethod('deleteTable', 1, fromChildItem.metauid)
          } else if (this.currentEventsArray[0].eventsType === 'removeTable') {
            // 逻辑删除
            this.evalTableRemoveRowMethod('removeTable', 1, fromChildItem.metauid)
          } else if (this.currentEventsArray[0].eventsType === 'recoverTable') {
            // 恢复
            this.evalTableRecoverRowMethod('recoverTable', 1, fromChildItem.metauid)
          } else if (this.currentEventsArray[0].eventsType === 'activeTable') {
            // 启用事件
            this.evalTableActiveRowMethod('activeTable', 1, fromChildItem.metauid)
          } else if (this.currentEventsArray[0].eventsType === 'deactiveTable') {
            // 停用事件
            this.evalTableDeactiveRowMethod('deactiveTable', 1, fromChildItem.metauid)
          }
        } else {
          this.getEventsInfoByEventNo(this.currentEventsArray[0].eventsNo, this.currentEventsArray[0].eventsType, 1, fromChildItem.metauid)
        }
      }
    },
    // 打开关联的页面
    openDialog (fromChildItem) {
      if (fromChildItem && fromChildItem.eventsArray && fromChildItem.eventsArray.length) {
        if (fromChildItem.eventsArray[0].dialogUid) {
          this.retatedPageVisible = true
          this.relatedPageUid = fromChildItem.eventsArray[0].dialogUid
          this.clickRow = fromChildItem.clickRow
          this.dialogType = fromChildItem.eventsArray[0].eventsType
        } else {
          this.$message({
            message: '还没有指定需要打开的页面，请前往资源管理进行配置',
            type: 'warning'
          })
        }
      }
    },
    // 关闭关联的页面时(需要刷新页面)
    closeDynamicMenuDialogSuccess () {
      this.retatedPageVisible = false
      this.init()
    },
    // 刷新当前页面
    reloadCurrentPage () {
      this.init()
    }
  },
  watch: {
    // 监听路由的变化
    '$route': {
      handler: function (val, oldVal) {
        if (this.$route.path === '/dashboard/dynamicWorkflowMenu') {
          this.init()
        }
      }
    }
  }
}
